#include "networker.h"

NetWorker::NetWorker()
{

}
void NetWorker::getNetList(QStringList & list)
{
    // 获取本机的网络接口列表
    QList<QNetworkInterface> ifaceList = QNetworkInterface::allInterfaces();
    for (int i = 0; i < ifaceList.count(); i++){
        QNetworkInterface var = ifaceList.at(i);

        bool isRealIp=false;
        QString netText="";
        QString netName=var.humanReadableName();
        QString hardwareAddress=var.hardwareAddress();
        // 排除 VMware虚拟网卡、Hyper-V 虚拟网卡
        if(netName.startsWith("VMware")
                ||netName.startsWith("vEthernet")
                ||netName.startsWith("VirtualBox")
                ||hardwareAddress==""
                ){
            continue;
        }
        netText.append(netName).append("::");
//        qDebug() << "########## 设备%1 ############"<<i;
//        qDebug() << "接口名称：" << netName;
//        qDebug() << "设备名称：" << var.name();
//        qDebug() << "硬件地址：" << hardwareAddress;

        // 读取一个IP地址的关联信息列表
        QList<QNetworkAddressEntry> entryList = var.addressEntries();
        foreach(QNetworkAddressEntry entry, entryList){
            QString netmask=entry.netmask().toString();
            bool isIpV6=netmask.startsWith("ffff:");
            bool broadCastIsNull=entry.broadcast().isNull();
            if(!isIpV6&&!broadCastIsNull){
                isRealIp=true;
                netText.append(entry.ip().toString());
            }
//            qDebug() << "IP: " << entry.ip().toString();
//            qDebug() << "子网掩码：" << entry.netmask().toString();
//            qDebug() << "广播地址：" << entry.broadcast().toString();

        }


        if(isRealIp){
            list.append(netText);

        }

    }
}
QString NetWorker::getIp(){
    QStringList netList;
    getNetList(netList);
    return netList.first().split("::").at(1);
}
void NetWorker::setIP(QString netName,QString ip, QString subnet, QString router)
{
    QProcess process(0);
    QString command;

#ifdef Q_OS_WIN
    command=QString("netsh interface ip set address %1 static %2 %3 %4");
#endif
#if defined (Q_OS_OSX) || defined (Q_OS_LINUX)
    command=QString("ifconfig %1 %2 netmask %3 up \n route add default gw %4");
#endif
    command=command.arg(netName).arg(ip).arg(subnet).arg(router);
    QStringList commands=command.split("\n");
    for(int i=0;i<commands.length();i++){
        qDebug()<<"执行命令："<<commands[i];
        process.start(commands[i]);
        process.waitForStarted();
        process.waitForFinished();
        qDebug()<<"命令执行反馈信息："<<QString::fromLocal8Bit(process.readAllStandardError());
    }



}
